package com.kaigejava.directexchange;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * Created by kaigejava on 2019/7/11.
 * direct 路由消费者
 */
public class Consumer4DirectExchange {

    public static void main(String[] args) throws  Exception {
        //1:创建一个connectioFactory工厂对象，并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置ip 端口 vhost等
        connectionFactory.setHost("192.168.31.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2：通过工厂对象获取到connection对象
        Connection connection = connectionFactory.newConnection();

        //3：通过connection对象获取到一个消息通信的通道 channel
        Channel channel = connection.createChannel();

        //4：声明 exchangename、exchangeType、queueName、routingkey
        String exchangeName ="test_direct_exchange";    //需要和生产者一致
        String exchangeType = "direct";
        String queueName = "test_direct _queue";
        String routingkEY ="test.direct.key";   //需要和生产者一致
        //5：设置channel
        //声明交换机
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
        //声明队列
        channel.queueDeclare(queueName,false,false,false,null);
        //建立绑定关系
        channel.queueBind(queueName,exchangeName,routingkEY);

        //是否持久化消息
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //参数：队列名称、是否自动、消费者
        channel.basicConsume(queueName,true,consumer);
        while(true){
            //获取消息。如果没有消息 这一步会阻塞
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String (delivery.getBody());
            System.out.println("消费者收到的消息为:"+msg);
        }

    }
}
